package cn.schoolwow.quickapi.module.business.api.flow;

import cn.schoolwow.quickapi.module.business.api.domain.API;
import cn.schoolwow.quickapi.module.common.domain.APIDocument;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import org.apache.commons.lang3.StringUtils;

public class SetRequestAndResponsePropertyFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        APIDocument apiDocument = flowContext.checkInstanceData(APIDocument.class);

        StringBuilder builder = new StringBuilder();
        for(API api:apiDocument.apiList){
            builder.setLength(0);
            builder.append("请求报文:\r\n\r\n");
            builder.append(api.requestMethod+" "+api.url+"\r\n");
            if(!"/".equalsIgnoreCase(api.contentType)){
                builder.append("ContentType: "+api.contentType);
            }
            for(String key:api.headerMap.keySet()){
                builder.append(key+": "+api.headerMap.getString(key));
            }
            builder.append("\r\n\r\n");

            {
                String requestBody = api.requestBody;
                if(StringUtils.isBlank(requestBody)){
                    requestBody = "无\r\n";
                }
                builder.append(requestBody+"\r\n");
            }
            builder.append("\r\n响应报文:\r\n\r\n");
            {
                String responseBody = api.responseBody;
                if(StringUtils.isBlank(responseBody)){
                    responseBody = "无\r\n";
                }
                builder.append(responseBody+"\r\n");
            }
            api.requestAndResponse = builder.toString();
        }
    }

    @Override
    public String name() {
        return "设置请求和响应属性";
    }
}
